from django.core.mail import send_mail
from django.shortcuts import render
from django.conf import settings
# Create your views here.
from rest_framework.views import APIView
from rest_framework.response import Response
from django.contrib.auth.hashers import make_password, check_password
from .models import *
from .ser import *
from itsdangerous import TimedJSONWebSignatureSerializer,SignatureExpired
import re
import redis
from .tasks import send_email_task
token_serializer = TimedJSONWebSignatureSerializer(settings.SECRET_KEY, 1800)
login_ser = TimedJSONWebSignatureSerializer(settings.SECRET_KEY, 86400)
r=redis.Redis(host='127.0.0.1',port=6379, db=5)
# send_mail
#注册

class CateView(APIView):
    def post(self,request):
        cate_id = request.data.get("cate_id")
        cate_name = request.data.get('cate_name')
        if not all([cate_id,cate_name]):
            return Response({'msg':'数据不完整','code':400})
        cate_obj = Cate.objects.filter(cate_name=cate_name)
        if cate_id == '0':
            if cate_obj:
                return Response({'msg':'分类已存在','code':400})
            cate_data = {'cate_name':cate_name}
            
class RoleView(APIView):
    def post(self,request):
        #获取网页，提交数据
        name = request.data.get('name')
        #获取数据库内容，用来判断角色
        obj_role=Role.objects.filter(name=name)
        if obj_role:
            return Response({'msg':'角色存在','code':201})
        role_ser=Roleser(data=request.data)
        if role_ser:
            role_ser.is_valid()
            role_ser.save()
            return Response({'msg':'添加成功','code':200})
        else:
            return Response({'error':role_ser.errors})

class RegisterView(APIView):
    def post(self,request):
        username = request.data.get('username')
        password1 = request.data.get('password1')
        password2 = request.data.get('password2')
        phone = request.data.get('phone')
        email = request.data.get('email')
        role_id = request.data.get('role')

        if not all([username , password1 , password2 , phone , email , role_id]):
            return Response({'msg':'数据不完整','code':400})
        phone_re = re.compile(r'^1(3\d|4[4-9]|5[0-35-9]|6[67]|7[013-8]|8[0-9]|9[0-9])\d{8}$')
        if not re.search(phone_re, phone):
            return Response({'msg': '手机号不符合规范', 'code': 400})
        user_obj=User.objects.filter(username=username)

        if user_obj:
            return Response({'msg':'用户存在','code':202})

        if password1 == password2:
            user_data={
                'username': username,
                'password1': make_password(password1),
                'phone': phone,
                'email': email,
                'role': role_id,
            }
            user_ser=Userser(date=user_data)
            if user_ser.is_valid():
                user_ser.save()
                user_info = {'user_id' : user_ser.data.get('id')}
                token = token_serializer.dumps(user_info).decode() #序列化完成以后，是bytes数据，需要decode()进行肌肉吗
                #发邮件 异步发送，需要一个code
                send_email_task.delay(username, token, email)

                return Response({'msg':'注册成功','code':200})
            else:
                return Response({'error': user_ser.errors})
        else:
            return Response({'msg': '两次密码不一致','code':400})


class ActiveView(APIView):
    def get(self,request):
        print(request.query_params.get('token'))
        try:
            user_info = User.objects.loads(request.query_params.get('token'))
            print(user_info)
            user_obj = User.objects.get(pk=user_info.get('user_id'))
            user_obj.staute = 1
            user_obj.save()
            return Response({'msg':'ok' , 'code':200})
        except SignatureExpired:
            return Response({'msg': '邮件过期','code':400})

# class LoginView(APIView):
#     '''
#     @author:
#     @date:2020-09-28
#     '''
#     def post(self,request):
#         #1.获取网页提交数据
#         username = request.date.get('username')
#         password = request.date.get('password')
#         # 2.获取用户数据对象
#         user_obj = User.objects.filter(username=username).first()
#         # 3.判断用户是否存在
#         if user_obj:
#             # 存在时，进行密码对比
#             if check_password(password,user_obj.password):
#                 user_info = ('user_id' : user_obj.pk)
#                 token = login_ser.dumps(user_info).decode()
#                 return Response({'msg':'ok','code':200, token ,'username':username , 'role':user_obj.role.name})
#             else:
#                 # 不存在时，返回用户或者密码不对
#                 return Response({'msg':'用户名或者密码不正确','code':400})
#
#         else:
#             return Response({'msg':'用户名或者密码不正确','code':400})

class IsUserName(APIView):
    def get(self,request):
        username = request.query_params.get('username')
        user_info = r.get(username)
        if user_info:
            return Response({"msg":'角色存在','code':400})
        else:
            return Response({'msg':'创建成功','code':200})
import requests
class CallBackView(APIView):
    def post(self,request):
        code = request.data.get('code')

        request_data = {
            'code':code,
            'client_id':'334174445',
            'clint_secret':'',
            'grant_type':'',
            
        }
        res_json = res.json()
        access_token = res_json.get('uid')
        auth_uid = res_json.get(url=''.format(access_token,auth_uid))



'''
1，申请新浪微博开放平台上的开发人员
2，注册应该
3，拼接获取授权的路由
http
4, 通过code . app key, grant_type,regdirect
'''










































































